var nxlsx = require('node-xlsx');
var fs = require('fs');
const path = require("path");
const xlsx = require('xlsx');
async function exportExcel(params) {
    var excelData = [];
    for (const key in params.tables) {
        var addInfo = {};
        addInfo.name = params.tables[key]['sheet'];
        addInfo.data = params.tables[key]['data'];
        excelData.push(addInfo);
    }
    var buffer = nxlsx.build(excelData);
    try {
        await fs.writeFileSync(__dirname + `/../../public/files/${params.title}.xlsx`, buffer);
        return true;
    } catch (error) {
        return false;
    }
}

function writeFile(path,write) {
    // const filePath = path.join(__dirname, '../../public/files/料架计算表格.xlsx');
    const workbook = xlsx.readFile(path);
    // 获取第一个工作表的名称
    const sheetName = workbook.SheetNames[5];
    // 获取第一个工作表
    const sheet = workbook.Sheets[sheetName];
    // 将工作表转换为JSON格式
    const data = xlsx.utils.sheet_to_json(sheet);
    // 打印数据
    const jsonData = JSON.stringify(data, null, 2);
    // path.join(__dirname, '../../public/files/料架计算表格.json')
    fs.writeFile(write, jsonData, 'utf8', (err) => {
        if (err) throw err;
        console.log('文件已保存');
    });
}

function readFile() {
    const filePath = path.join(__dirname, '../../public/files/料架计算表格.json');
    const data = fs.readFileSync(filePath, 'utf8');
    const jsonData = JSON.parse(data);
    return jsonData;
}

module.exports = {
    exportExcel,
    writeFile,
    readFile
}